package org.jeecg.modules.xmss.controller;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.*;
import org.jeecg.modules.system.entity.SysLog;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.StringUtil;
import org.jeecg.modules.xmss.entity.XmssIdea;
import org.jeecg.modules.xmss.entity.XmssTowns;
import org.jeecg.modules.xmss.mapper.XmssIdeaMapper;
import org.jeecg.modules.xmss.mapper.XmssIdeaTypeMapper;
import org.jeecg.modules.xmss.mapper.XmssSuperviseMapper;
import org.jeecg.modules.xmss.service.IXmssIdeaService;
import org.jeecg.modules.xmss.service.IXmssSuperviseService;
import org.jeecg.modules.xmss.service.IXmssTownsService;
import org.jeecg.modules.xmss.util.Base64Encoder;
import org.jeecg.modules.xmss.util.WebFileUtils;
import org.jeecg.modules.xmss.vo.XmssIdeaAddVo;
import org.jeecg.modules.xmss.vo.XmssIdeaDetialVo;
import org.jeecg.modules.xmss.vo.XmssIdeaPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 选民意见建议表
 * @Author: jeecg-boot
 * @Date:   2020-09-18
 * @Version: V1.0
 */
@Api(tags="选民意见建议表")
@RestController
@Valid
@RequestMapping("/xmss/xmssIdea")
@Slf4j
public class XmssIdeaController {

	@Autowired
	private IXmssIdeaService xmssIdeaService;

	 @Autowired
	 private IXmssTownsService iXmssTownsService;

	 @Autowired
	 private IXmssSuperviseService xmssSuperviseService;

	 @Autowired
	 private ISysUserService sysUserService;

	 @Autowired
	 private XmssSuperviseMapper xmssSuperviseMapper;

	 @Autowired
	 private IXmssSuperviseService iXmssSuperviseService;

	 @Autowired
	 private XmssIdeaMapper xmssIdeaMapper;
	 @Autowired
	 private  XmssIdeaTypeMapper xmssIdeaTypeMapper;
	/**
	 * 分页列表查询
	 *
	 * @param
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "意见建议表-分页列表查询")
	@ApiOperation(value="公众号接口--意见建议表-分页列表查询", notes="jqk 小程序状态 1.待处理  2.处理中 3.已处理  4已评价 5已驳回")
	@GetMapping(value = "/list")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "每页数量", required = false, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "userId", value = "政府管理员、人大代表的事件列表 -- 传参 登录返回的用户id", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "openId", value = "个人看自己的意见列表-- 传参 微信openId -- 个人标识", required = false, dataType = "String", paramType = "query"),
	})
	public Result<?> queryPageList(
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   @RequestParam(name="userId",required = false) String userId,
								   @RequestParam(name="openId",required = false) String openId,
								   HttpServletRequest req) {
		if(!StringUtils.isNotEmpty(userId) && !StringUtils.isNotEmpty(openId)){
			return Result.OK("暂无数据");
		}
		XmssIdea xmssIdea = new XmssIdea();
		SysUser byId = sysUserService.getById(userId);
		String relTenantIds = "";
		if(byId != null ){
            relTenantIds = byId.getRelTenantIds();
        }
		IPage<XmssIdea> pageList = null;
		if(byId != null && byId.getUserIdentity() != null && byId.getUserIdentity() == 2){//政府人员  只看待处理
			xmssIdea.setTownsId(relTenantIds);
			QueryWrapper<XmssIdea> queryWrapper = QueryGenerator.initQueryWrapper(xmssIdea, req.getParameterMap());
			queryWrapper.orderByDesc("create_time");
			Page<XmssIdea> page = new Page<XmssIdea>(pageNo, pageSize);
			pageList = xmssIdeaService.page(page, queryWrapper);
		}
		if(StringUtils.isNotEmpty(openId)){//自己看到的
			xmssIdea.setOpenId(openId);
			QueryWrapper<XmssIdea> queryWrapper = QueryGenerator.initQueryWrapper(xmssIdea, req.getParameterMap());
			queryWrapper.orderByDesc("create_time");
			Page<XmssIdea> page = new Page<XmssIdea>(pageNo, pageSize);
			pageList = xmssIdeaService.page(page, queryWrapper);
		}
		if(StringUtils.isNotEmpty(userId) && byId.getType() == 1){//督办人员看到的
			pageList = xmssIdeaService.personIdea(userId,pageNo,pageSize);
		}
        if(StringUtils.isNotEmpty(userId) && byId.getType() == 2){//交办人员看到的
            pageList = xmssIdeaService.jbIdea(userId,pageNo,pageSize);
        }
		List<XmssIdea> records = pageList.getRecords();
		pageList.setRecords(records);

		return Result.OK(pageList);
	}

	public String getUrlByDh(String url){
		String allUrl = "";
		String[] split = url.split(",");
		for (int i = 0; i < split.length; i++) {

			String s = split[i];
			allUrl +=  MinioUtil.getMinioUrl() + MinioUtil.getBucketName()+ "/" + s + ",";
		}
		if(StringUtils.isNotEmpty(allUrl) && allUrl.substring(allUrl.length()-1).equals(",")){
			allUrl = allUrl.substring(0,allUrl.length()-1);
		}
		return allUrl;
	}

	 public String getMobileByJm(String mobile){
		 mobile = mobile.substring(0, 3) + "****" + mobile.substring(mobile.length() - 4);
		 return mobile;
	 }

	 /**
	  *   添加
	  *
	  * @param
	  * @return
	  */
	 @AutoLog(value = "公众号接口--选民意见建议表-图片上传")
	 @ApiOperation(value="公众号接口--选民意见建议表-图片上传", notes="jqk选民意见建议表-图片上传")
	 @PostMapping(value = "/pictrueUpload")

	 public Result<?> pictrueUpload(
			 @RequestParam(value = "file",required=false) MultipartFile file
	 ) throws IOException {
		 String url = "";
		 String fileName =  file.getOriginalFilename();
		 //String url = MinioUtil.uploadFile(WebFileUtils.byteToMultipartFile(bytes));
		 if(fileName.contains("JPEG") || fileName.contains("JPEG") || fileName.contains("PNG") || fileName.contains("png")|| fileName.contains("GIF")|| fileName.contains("gif")|| fileName.contains("TIFF")|| fileName.contains("tif")|| fileName.contains("bmp")){
			 byte[] bytes = WebFileUtils.compress(file.getBytes(), 0.1);
			 url = MinioUtil.uploadFileYasuo(WebFileUtils.byteToMultipartFile(bytes),file.getOriginalFilename());
		 }else {
			 url = MinioUtil.uploadFile(file);
		 }
		 return Result.OK(url);
	 }

	 /**
	  *   添加
	  *
	  * @param
	  * @return
	  */
	 @AutoLog(value = "公众号接口--选民意见建议表-图片上传1111111111")
	 @ApiOperation(value="公众号接口--选民意见建议表-图片上传", notes="jqk选民意见建议表-图片上传1111111111")
	 @PostMapping(value = "/pictrueUpload1")

	 public Result<?> pictrueUpload1(
			 @RequestParam(value = "file",required=false) MultipartFile file
	 ) throws IOException {
		 String url = "";
		 String fileName =  file.getOriginalFilename();
	 	//String url = MinioUtil.uploadFile(WebFileUtils.byteToMultipartFile(bytes));
		 if(fileName.contains("JPEG") || fileName.contains("JPEG") || fileName.contains("PNG") || fileName.contains("png")|| fileName.contains("GIF")|| fileName.contains("gif")|| fileName.contains("TIFF")|| fileName.contains("tif")|| fileName.contains("bmp")){
			 byte[] bytes = WebFileUtils.compress(file.getBytes(), 0.1);
		 	url = MinioUtil.uploadFileYasuo(WebFileUtils.byteToMultipartFile(bytes),file.getOriginalFilename());
		 }else {
			 url = MinioUtil.uploadFile(file);
		 }
	 	return Result.OK(url);
	 }

	/**
	 *   添加
	 *
	 * @param
	 * @return
	 */
	@AutoLog(value = "意见建议表-添加")
	@ApiOperation(value="公众号接口--意见建议表-添加", notes="jqk")
	@PostMapping(value = "/addOne")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "name", value = "姓名", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "mobile", value = "手机号码", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "idea", value = "内容 5--255个字符", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "ideaType", value = "意见类型", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "openId", value = "微信openId -- 个人标识", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "publicOpenId", value = "公众号标识---区分乡镇的", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "1图片   2视频", required = false, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "url", value = "图片  视频的url 逗号分开", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "longitude", value = "经度（纵坐标）", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "latitude", value = "纬度（横坐标）", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "address", value = "地址", required = false, dataType = "String", paramType = "query"),
	})
	public Result<?> addOne(
			@RequestParam(name="name",required=true) String name,
			@RequestParam(name="mobile",required=true) String mobile,
			@RequestParam(name="idea",required=true) String idea,
			@RequestParam(name="openId",required=true) String openId,
			@RequestParam(name="publicOpenId",required=true) String publicOpenId,
			@RequestParam(name="url",required=false) String url,
			@RequestParam(name="ideaType",required=true) String ideaType,
			@RequestParam(name="type",required=true) String type,
			@RequestParam(name="longitude",required=false) String longitude,
			@RequestParam(name="address",required=false) String address,
			@RequestParam(name="latitude",required=false) String latitude

	) throws ClientException {
		XmssTowns xmssTowns = iXmssTownsService.selectTownsByPublicOpenId(publicOpenId);
		if(xmssTowns != null){
			XmssIdea xmssIdea = new XmssIdea();
			xmssIdea.setName(name);
			xmssIdea.setMobile(mobile);
			xmssIdea.setIdea(idea);
			xmssIdea.setOpenId(openId);
			xmssIdea.setType(type);
			//上传图片和视频
			xmssIdea.setUrl(url);
			xmssIdea.setIdeaType(Integer.parseInt(ideaType));
			xmssIdea.setTownsId(xmssTowns.getId());
			xmssIdea.setLongitude(longitude);
			xmssIdea.setLatitude(latitude);
            xmssIdea.setAddress(address);
			xmssIdea.setCreateTime(new Date());
			xmssIdea.setUpdateTime(new Date());
			xmssIdeaService.saveMain(xmssIdea );

			//发送待处理短信
			JSONObject obj = new JSONObject();
			//obj.put("code", checkCode);
			//政府
			List<SysUser> zf = sysUserService.getUserListByDx("", "1");
			for (int i = 0; i < zf.size(); i++) {//
				DySmsHelper.sendSmsZll(zf.get(i).getPhone(), obj, xmssTowns.getTodoTemplateCode(),xmssTowns.getSign());
			}
			/*//乡镇
			List<SysUser> xz = sysUserService.getUserListByDx(xmssTowns.getId(), "2");
			for (int i = 0; i < xz.size(); i++) {
				DySmsHelper.sendSmsZll(xz.get(i).getPhone(), obj, xmssTowns.getTodoTemplateCode(),xmssTowns.getSign());
			}*/
		}else{
			return Result.OK("您没有权限！");
		}
		return Result.OK("添加成功！");
	}

	 /**
	  *   添加
	  *
	  * @param
	  * @return
	  */
	 //@AutoLog(value = "选民意见建议表-添加222")
	 //@ApiOperation(value="选民意见建议表-添加222", notes="选民意见建议表-添加222")
	 @RequestMapping(value = "/add", method = RequestMethod.POST)
	 public Result<?> add(
			 @RequestBody XmssIdeaAddVo xmssIdeaAddVo
	 ) {
		 XmssIdea xmssIdea = new XmssIdea();
		 XmssTowns xmssTowns = iXmssTownsService.selectTownsByPublicOpenId(xmssIdeaAddVo.getPublicOpenId());
		 BeanUtils.copyProperties(xmssIdeaAddVo, xmssIdea);
		 xmssIdea.setTownsId(xmssTowns.getId());
		 xmssIdea.setCreateTime(new Date());
		 xmssIdea.setUpdateTime(new Date());
		 xmssIdeaService.saveMain(xmssIdea );
		 return Result.OK("添加成功！");
	 }

	/**
	 *  编辑
	 *
	 * @param xmssIdeaPage
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody XmssIdeaPage xmssIdeaPage) {
		XmssIdea xmssIdea = new XmssIdea();
		BeanUtils.copyProperties(xmssIdeaPage, xmssIdea);
		XmssIdea xmssIdeaEntity = xmssIdeaService.getById(xmssIdea.getId());
		xmssIdeaService.updateMain(xmssIdea);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		xmssIdeaService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	//@AutoLog(value = "选民意见建议表-批量删除")
	//@ApiOperation(value="选民意见建议表-批量删除", notes="选民意见建议表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.xmssIdeaService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "意见建议表-通过id查询")
	@ApiOperation(value="意见建议表-通过id查询", notes="")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam String id) {
	    List<String> getresult =new ArrayList<>();
        List<String> getresults =new ArrayList<>();
		XmssIdea xmssIdea = xmssIdeaService.getById(id);
		if(xmssIdea==null) {
			return Result.error("未找到对应数据");
		}

        LoginUser sysUsers = (LoginUser) SecurityUtils.getSubject().getPrincipal();

            List <String> xmssSupervise = xmssSuperviseMapper.getByIds(xmssIdea.getId(),!"".equals(sysUsers.getRelTenantIds())?sysUsers.getRelTenantIds():null,"1");
            xmssSupervise.stream().forEach(i-> {
                xmssIdea.setSupervisionName( i+"、");
            });



		/*if(StringUtils.isNotEmpty(xmssIdea.getUrl())) {
		    if("1".equals(xmssIdea.getType())){
            List<String> result = Arrays.asList(xmssIdea.getUrl().split(","));
            result.stream().forEach(e -> {
                getresult.add(MinioUtil.getMinioUrl() + MinioUtil.getBucketName()+"/"+e);
                xmssIdea.setUrl("");
            });
            }else{
                xmssIdea.setUrl(MinioUtil.getMinioUrl() + MinioUtil.getBucketName()+"/"+xmssIdea.getUrl());
            }
		}

        if(StringUtils.isNotEmpty(xmssIdea.getAnswerUrl())) {
        	if(xmssIdea.getAnswerType()==1){
            List<String> result = Arrays.asList(xmssIdea.getAnswerUrl().split(","));
            result.stream().forEach(e -> {
                getresults.add(MinioUtil.getMinioUrl() + MinioUtil.getBucketName()+"/"+e);
                xmssIdea.setAnswerUrl("");
            });
        	}else{
				xmssIdea.setAnswerUrl(MinioUtil.getMinioUrl() + MinioUtil.getBucketName()+"/"+xmssIdea.getAnswerUrl());
			}
        }*/


		XmssIdeaDetialVo xmssIdeaDetial = new XmssIdeaDetialVo();
		BeanUtils.copyProperties(xmssIdea,xmssIdeaDetial);

		return Result.OK(xmssIdeaDetial);

	}

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "公众号接口--意见建议表-通过id查询")
	 @ApiOperation(value="公众号接口--意见建议表-通过id查询", notes="jqk")
	 @GetMapping(value = "/publicQueryById")
	 @ApiImplicitParams({
			 @ApiImplicitParam(name = "id", value = "事件id", required = false, dataType = "String", paramType = "query"),
			 @ApiImplicitParam(name = "userId", value = "获取详情的人员id，选填", required = false, dataType = "String", paramType = "query"),
	 })
	 public Result<?> publicQueryById(@RequestParam String id,@RequestParam (required = false) String userId) {
		 XmssIdea xmssIdea = xmssIdeaMapper.selectIdeaById(id);
		 List<Object> list = new ArrayList<>();

		 if(xmssIdea==null) {
			 return Result.error("未找到对应数据");
		 }else{
			 Map<String, Object> map = new HashMap<>();
			 List<String> strings = xmssSuperviseMapper.selectDbNameByIdeaId(xmssIdea.getId());
			 String names = strings.toString().replace("[", "").replace("]", "");

			 List<SysUser> sysUsers = xmssSuperviseMapper.selectDbPictureByIdeaId(xmssIdea.getId());
			 List<SysUser> jbUser = xmssSuperviseMapper.selectJbPictureByIdeaId(xmssIdea.getId());


			 if(strings.size() > 0){
				 xmssIdea.setSupervisionName(names);
			 }else {
				 xmssIdea.setSupervisionName("");
			 }
			 if(xmssIdea.getDbTime() != null && xmssIdea.getDbTime().toString().length() > 5){
				 map.put("db", xmssIdea.getDbTime());
				 map.put("supervisionName",names);
				 if(sysUsers.size() > 0){
					 map.put("picture", sysUsers.get(0).getAvatar());
				 }
				 list.add(map);
			 }
			 if(xmssIdea.getDealTime() != null && xmssIdea.getDealTime().toString().length() > 5){
				 map = new HashMap<>();//交办查看时间
				 if(jbUser.size() > 0){
					 map.put("picture", jbUser.get(0).getAvatar());
					 map.put("supervisionName",jbUser.get(0).getRealname());
				 }
				 map.put("zf", xmssIdea.getDealTime());
				 list.add(map);

				 map = new HashMap<>();//交办查看时间就等于处理中时间
				 if(jbUser.size() > 0){
					 map.put("picture", jbUser.get(0).getAvatar());
					 map.put("supervisionName",jbUser.get(0).getRealname());
				 }
				 map.put("dealing", xmssIdea.getDealTime());
				 list.add(map);
			 }

		 	if(xmssIdea.getAnswerTime() != null && xmssIdea.getAnswerTime().toString().length() > 5){
				map = new HashMap<>();
				if(jbUser.size() > 0){
					map.put("picture", jbUser.get(0).getAvatar());
					map.put("supervisionName",jbUser.get(0).getRealname());
				}
				map.put("answer", xmssIdea.getAnswerTime());
				list.add(map);
			}
		 	xmssIdea.setStateList(list);
		 }
		 return Result.OK(xmssIdea);

	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "1评价  2回复  3整个驳回 4督办确认事件 5督办驳回 6交办确认事件 7交办驳回")
	 @ApiOperation(value="公众号接口--1评价  2回复  3整个驳回 4督办确认事件 5督办驳回 6交办确认事件 7交办驳回", notes="jqk")
	 @PostMapping(value = "/supervise")
	 @ApiImplicitParams({
			 @ApiImplicitParam(name = "id", value = "意见建议id", required = false, dataType = "String", paramType = "query"),
			 @ApiImplicitParam(name = "type", value = "1评价  2回复  3整个驳回 4督办确认事件 5督办驳回 6交办确认事件 7交办驳回", required = false, dataType = "Integer", paramType = "query"),
			 @ApiImplicitParam(name = "answerType", value = "回复的文件类型 1图片  2视频", required = false, dataType = "Integer", paramType = "query"),
			 @ApiImplicitParam(name = "state", value = "事情星级  1一星 2二星 3三星 4四星 5五星", required = false, dataType = "Integer", paramType = "query"),
			 @ApiImplicitParam(name = "starDb", value = "督办的星级评价  1一星 2二星 3三星 4四星 5五星", required = false, dataType = "Integer", paramType = "query"),
			 @ApiImplicitParam(name = "content", value = "回复的内容", required = false, dataType = "String", paramType = "query"),
			 @ApiImplicitParam(name = "url", value = "回复的图片或者视频", required = false, dataType = "String", paramType = "query"),
			 @ApiImplicitParam(name = "userId", value = "操作人的id", required = false, dataType = "String", paramType = "query"),
	 })
	 public Result<?> supervise(@RequestParam(name="id",required=true) String id,
								@RequestParam(name="state",required=false) Integer state,
								@RequestParam(name="starDb",required=false) Integer starDb,
								@RequestParam(name="content",required=false) String content,
								@RequestParam(name="url",required=false) String url,
								@RequestParam(name="type",required=true) Integer type,
								@RequestParam(name="userId",required=false) String userId,
								@RequestParam(name="answerType",required=false) Integer answerType
								) throws ClientException {
		 XmssIdea xmssIdea = xmssIdeaService.getById(id);
		 if(xmssIdea==null) {
			 return Result.error("未找到对应数据");
		 }else{
			xmssIdeaService.manageIdea(id,state,content,url,type,answerType,starDb,userId);
		 }
		 return Result.OK("处理成功!");
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param xmssIdea
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, XmssIdea xmssIdea) {
		List<String> getresult =new ArrayList<>();
		LoginUser sysUsers = (LoginUser) SecurityUtils.getSubject().getPrincipal();
      // Step.1 组装查询条件查询数据
      QueryWrapper<XmssIdea> queryWrapper = QueryGenerator.initQueryWrapper(xmssIdea, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<XmssIdea> queryList = xmssIdeaService.list(queryWrapper);

      //处理数据库查询的数据
		queryList.stream().forEach(e -> {

			if(e.getUrl()!=null && !"".equals(e.getUrl())) {
				e.setUrl(MinioUtil.getMinioUrl() + MinioUtil.getBucketName() + "/" + e.getUrl());
			}

					if(e.getAnswerUrl()!=null && !"".equals(e.getAnswerUrl())) {
						e.setAnswerUrl(MinioUtil.getMinioUrl() + MinioUtil.getBucketName() + "/" + e.getAnswerUrl());
					}


			/*if(StringUtils.isNotEmpty(xmssIdea.getAnswerUrl())) {
				if(xmssIdea.getAnswerType()==1){
					List<String> result = Arrays.asList(xmssIdea.getAnswerUrl().split(","));
					result.stream().forEach(j -> {

						xmssIdea.setAnswerUrl(result.size()<=2? MinioUtil.getMinioUrl() + MinioUtil.getBucketName()+"/"+j+" ," :MinioUtil.getMinioUrl() + MinioUtil.getBucketName()+"/"+j);
					});
				}else{
					xmssIdea.setAnswerUrl(MinioUtil.getMinioUrl() + MinioUtil.getBucketName()+"/"+xmssIdea.getAnswerUrl());
				}
			}


			if(StringUtils.isNotEmpty(xmssIdea.getAnswerUrl())) {
				if(xmssIdea.getAnswerType()==1){
					List<String> result = Arrays.asList(xmssIdea.getUrl().split(","));
					result.stream().forEach(j -> {

						xmssIdea.setUrl(result.size()<=2? MinioUtil.getMinioUrl() + MinioUtil.getBucketName()+"/"+j+" ," :MinioUtil.getMinioUrl() + MinioUtil.getBucketName()+"/"+j);
					});
				}else{
					xmssIdea.setUrl(MinioUtil.getMinioUrl() + MinioUtil.getBucketName()+"/"+xmssIdea.getUrl());
				}
			}*/


			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");



					e.setCreateTimeRoLead(format.format(e.getCreateTime()));

					if(e.getUpdateTime()!=null && !"".equals(e.getUpdateTime())) {
						e.setUpdateTimeRoLead(format.format(e.getUpdateTime()));
					}

			switch (e.getAppState()) {
				case 1:
					e.setAppStateRoLead("待处理 ");
					break;

				case 2:
					e.setAppStateRoLead("处理中");
					break;

				case 3:
					e.setAppStateRoLead("已处理");
					break;

				case 4:
					e.setAppStateRoLead("已评价");
					break;

				case 5:
					e.setAppStateRoLead("已驳回");
					break;

			}


			switch (e.getIsRead()) {
				case 0:
					e.setIsReadRoLead("未读 ");
					break;

				case 1:
					e.setIsReadRoLead("已读");
					break;

			}


			e.setMobile(e.getMobile());
			List <String> xmssSupervise = xmssSuperviseMapper.getByIds(e.getId(),!"".equals(sysUsers.getRelTenantIds())?sysUsers.getRelTenantIds():null,"1");
			xmssSupervise.stream().forEach(i-> {
				e.setSupervisionName( e.getSupervisionName()!=null ? e.getSupervisionName()+"、"+i :i);
			});
			//遍历交办人员姓名返回
			List <String> getJiaoBan = xmssSuperviseMapper.getByIde(e.getId(),!"".equals(sysUsers.getRelTenantIds())?sysUsers.getRelTenantIds():null,"2");
			getJiaoBan.stream().forEach(i-> {
				e.setAssignName( e.getAssignName()!=null ? e.getAssignName()+"、"+i :i);
			});


		});




      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<XmssIdea> xmssIdeaList = new ArrayList<XmssIdea>();
      if(oConvertUtils.isEmpty(selections)) {
          xmssIdeaList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          xmssIdeaList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<XmssIdeaPage> pageList = new ArrayList<XmssIdeaPage>();
      for (XmssIdea main : xmssIdeaList) {
          XmssIdeaPage vo = new XmssIdeaPage();
          BeanUtils.copyProperties(main, vo);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "选民意见建议表列表");
      mv.addObject(NormalExcelConstants.CLASS, XmssIdeaPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("选民意见建议表数据", "导出人:"+sysUser.getRealname(), "选民意见建议表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
		  ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<XmssIdea> list = ExcelImportUtil.importExcel(file.getInputStream(), XmssIdea.class, params);

              for (XmssIdea page : list) {

                      XmssIdea po = new XmssIdea();
                      BeanUtils.copyProperties(page, po);
                      po.setAppState(1);
                      po.setUrl(page.getUrl());
                     /* if (page.getUrl() != null && !"".equals(page.getUrl())) {
                          MultipartFile files = WebFileUtils.base64ToMultipart("data:image/jpg;base64," + getImgUrlToBase64(page.getUrl()));
                          po.setUrl(MinioUtil.uploadFile(files));
					  }*/

                      po.setCreateTime(simpleDateFormat.parse(page.getCreateTimeRoLead()));
                      LoginUser sysUsers = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                      po.setTownsId(sysUsers.getRelTenantIds());
				  if (page.getName() != null && page.getMobile()!=null && page.getIdea()!=null ) {
					  xmssIdeaService.saveMain(po);
				  }

              }
              return Result.OK("文件导入成功！数据行数:" + list.size());


          } catch (Exception e) {
              log.error(e.getMessage(), e);
              return Result.error("文件导入失败:" + e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
        return Result.OK("文件导入失败！");
    }



	 /**
	  * pc端分页列表查询
	  *
	  * @param
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = " pc端选民意见建议表-分页列表查询")
	 @ApiOperation(value="办事管理-事件列表", notes="选民意见建议表-分页列表查询")
	 @GetMapping(value = "/queryPageLists")
	 public Result<?> queryPageLists(XmssIdea xmssIdea,
									 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									 HttpServletRequest req) {
		 Result<?> result = new Result<IPage<SysLog>>();
		 XmssIdea getXmssIdea=new XmssIdea();
		 LambdaQueryWrapper<XmssIdea> query = new LambdaQueryWrapper<XmssIdea>();
		 Page<XmssIdea> page = new Page<XmssIdea>(pageNo, pageSize);

		 //姓名关键词
		 String name = xmssIdea.getName();
		 if(oConvertUtils.isNotEmpty(name)) {
			 query.like(XmssIdea::getName,name);
		 }
		 //时间关键词
		 String getTime = xmssIdea.getStarTime();
		 if(oConvertUtils.isNotEmpty(getTime)) {
			 query.ge(XmssIdea::getCreateTime,getTime);
		 }

		 //时间关键词
		 String getUpdateTime = xmssIdea.getEndTime();
		 if(oConvertUtils.isNotEmpty(getUpdateTime)) {
			 query.lt(XmssIdea::getUpdateTime,getUpdateTime);
		 }


		 //状态关键词
		 String getAppState = null!=xmssIdea.getAppState() && !"".equals(xmssIdea.getAppState())  ?xmssIdea.getAppState().toString():null;
		 if(oConvertUtils.isNotEmpty(getAppState)) {
			 query.eq(XmssIdea::getAppState ,getAppState);
		 }

		 //镇关键词

		 LoginUser sysUsers = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String username=sysUsers.getUsername();
		 if(!"admin".equals(username)) {
			 query.eq(XmssIdea::getTownsId, sysUsers.getRelTenantIds());
		 }

		 query.orderByDesc(XmssIdea::getCreateTime);

		 IPage<XmssIdea> pageList = xmssIdeaService.page(page, query);
		  pageList.getRecords().stream().forEach(e -> {
			 e.setMobile(StringUtil.get(e.getMobile()));
			 //遍历督办人员姓名返回
			 List <String> xmssSupervise = xmssSuperviseMapper.getByIds(e.getId(),!"".equals(sysUsers.getRelTenantIds())?sysUsers.getRelTenantIds():null,"1");
			 xmssSupervise.stream().forEach(i-> {
				 e.setSupervisionName( e.getSupervisionName()!=null ? e.getSupervisionName()+"、"+i :i);
			 });
				//遍历交办人员姓名返回
			  List <String> getJiaoBan = xmssSuperviseMapper.getByIde(e.getId(),!"".equals(sysUsers.getRelTenantIds())?sysUsers.getRelTenantIds():null,"2");
			  getJiaoBan.stream().forEach(i-> {
				  e.setAssignName( e.getAssignName()!=null ? e.getAssignName()+"、"+i :i);
			  });

		 });
		 return Result.OK(pageList);
	 }



	 /**
	  * 统计分析--办事统计
	  *
	  * @return
	  */
	 @AutoLog(value = "统计分析--办事统计")

	 @ApiImplicitParams({
			 @ApiImplicitParam(name = "type", value = "1：周  2：月 3：年   deal：已办   noDeal：未办 ", required = false, dataType = "String", paramType = "query"),
	 })
	 @ApiOperation(value = "统计分析--办事统计", notes = "统计分析--办事统计")
	 @GetMapping(value = "/ideaDealData")
	 public Result<Object> ideaDealData(@RequestParam(name = "type", required = false) Integer type){
		 Map<String, Object> map = new HashMap<>();

		 map = xmssIdeaService.thingData(type);
		 return Result.ok(map);
	 }

	 /**
	  * 统计分析--评价统计
	  *
	  * @return
	  */
	 @AutoLog(value = "统计分析--评价统计")
	 @ApiImplicitParams({
			 @ApiImplicitParam(name = "type", value = "1：周  2：月 3：年   yes：满意   no：不满意  general：一般", required = false, dataType = "String", paramType = "query"),
			 @ApiImplicitParam(name = "personType", value = "1：督办  2：事件 ", required = false, dataType = "String", paramType = "query"),
	 })
	 @ApiOperation(value = "统计分析--评价统计", notes = "jqk统计分析--评价统计")
	 @GetMapping(value = "/ideaPjData")
	 public Result<Object> ideaPjData(
	 		@RequestParam(name = "type", required = false) Integer type,
	 		@RequestParam(name = "personType", required = false) Integer personType
			){


		 Map<String, Object> map = xmssIdeaService.pjData(type,personType);
		 return Result.ok(map);
	 }

	 /**
	  * 统计分析--评价统计
	  *
	  * @return
	  */
	 @AutoLog(value = "首页--今日已办、待处理、已完成、好评数")
	 @ApiOperation(value = "首页-- todayFinish 今日已办、todo 待处理、finish 已完成、yes 好评数", notes = "首页--今日已办、待处理、已完成、好评数")
	 @GetMapping(value = "/indexData")
	 public Result<Object> indexData(){
		 Map<String, Object> map = xmssIdeaService.indexData();
		 return Result.ok(map);
	 }

	 /**
	  * 首页-意见反馈件数统计
	  *
	  * @return
	  */
	 @AutoLog(value = "首页-意见反馈件数统计")
	 @ApiOperation(value = "首页-意见反馈件数统计", notes = "首页-意见反馈件数统计")
	 @GetMapping(value = "/indexIdeaData")
	 public Result<Object> indexIdeaData(){
		 Map<String,Object> map = xmssIdeaService.indexIdeaData();
		 return Result.ok(map);
	 }



	 /**
	  * 导出word文档
	  *
	  * @param request
	  * @param xmssIdea
	  */
	 @RequestMapping(value = "/selectExportXls")
	 public ModelAndView selectExportXls(HttpServletRequest request, XmssIdea xmssIdea) {


		 return null;
	 }

	 /**
	  * 事件word文档下载
	  *
	  * @return
	  */
	 @AutoLog(value = "事件word文档下载")
	 @ApiOperation(value = "首页-事件word文档下载", notes = "事件word文档下载")
	 @GetMapping(value = "/downWords")
	 public void downWords(HttpServletRequest request, HttpServletResponse response) {
		 xmssIdeaService.downWords(request, response);
	 }



	 /**
	  * 将网络图片转换成Base64编码字符串
	  *
	  * @param
	  * @return
	  */
	 @AutoLog(value = "将网络图片转换成Base64编码字符串")
	 @ApiOperation(value = "将网络图片转换成Base64编码字符串", notes = "将网络图片转换成Base64编码字符串")
	 @GetMapping(value = "/getImgUrlToBase64")
	 public static String getImgUrlToBase64(String imgUrl) {
		 InputStream inputStream = null;
		 ByteArrayOutputStream outputStream = null;
		 byte[] buffer = null;
		 try {
			 // 创建URL
			 URL url = new URL(imgUrl);
			 // 创建链接
			 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			 conn.setRequestMethod("GET");
			 conn.setConnectTimeout(5000);
			 inputStream = conn.getInputStream();
			 outputStream = new ByteArrayOutputStream();
			 // 将内容读取内存中
			 buffer = new byte[1024];
			 int len = -1;
			 while ((len = inputStream.read(buffer)) != -1) {
				 outputStream.write(buffer, 0, len);
			 }
			 buffer = outputStream.toByteArray();
		 } catch (IOException e) {
			 e.printStackTrace();
		 } finally {
			 if (inputStream != null) {
				 try {
					 // 关闭inputStream流
					 inputStream.close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
			 if (outputStream != null) {
				 try {
					 // 关闭outputStream流
					 outputStream.close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 // 对字节数组Base64编码
		 return "data:image/jpg;base64,"+Base64Encoder.encode(buffer);
	 }



     /**
      *  通过id编辑是否已读
      *
      * @param
      * @return
      */
     @GetMapping(value = "/editReadType")
     public Result<?> editReadType(@RequestParam String id) {
         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");//设置日期格式
         XmssIdea xmssIdea = new XmssIdea();
         xmssIdea.setId(id);
         xmssIdea.setIsRead(1);
         xmssIdea.setDbTime(new Date());
         xmssIdeaService.updateMain(xmssIdea);
         return Result.OK("修改成功!");
     }



	 /**
	  *  回显
	  *
	  * @param
	  * @return
	  */

	 @AutoLog(value = "回显")
	 @ApiOperation(value="回显", notes="回显")
	 @GetMapping(value = "/selectEcho")
	 public Result<?> selectEcho(@RequestParam String id) {
	 	Map<String ,Object> getmap=new HashMap();
		 LambdaQueryWrapper<XmssIdea> query = new LambdaQueryWrapper<XmssIdea>();
		 query.eq(XmssIdea::getId,id);
		 List <XmssIdea> xmssIdeaEntity = xmssIdeaMapper.selectList(query);

		 LoginUser sysUsers = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 xmssIdeaEntity.stream().forEach(e -> {
		 //遍历督办人员姓名返回
		 List <String> xmssSupervise = xmssSuperviseMapper.getById(e.getId(),!"".equals(sysUsers.getRelTenantIds())?sysUsers.getRelTenantIds():null,"1");
			 getmap.put("xmssSupervise",xmssSupervise);
		//遍历交办人员姓名返回
		 List <String> getJiaoBan = xmssSuperviseMapper.getByIdse(e.getId(),!"".equals(sysUsers.getRelTenantIds())?sysUsers.getRelTenantIds():null,"2");
			 getmap.put("getJiaoBan",getJiaoBan);
		 });
		 return Result.OK(getmap);
	 }


}
